package com.youlu.campus.service.wechat.impl;

import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.entity.VO.req.WechatTemplateMsgQueryVO;
import com.youlu.campus.entity.WechatConfigInfo;
import com.youlu.campus.entity.WechatTemplateMsg;
import com.youlu.campus.entity.complaint.ComplaintOrderInfo;
import com.youlu.campus.entity.complaint.MerchantComplaint;
import com.youlu.campus.service.wechat.WechatConfigInfoService;
import com.youlu.campus.service.wechat.WechatTemplateMsgService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WechatTemplateMsgServiceImpl implements WechatTemplateMsgService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private WechatConfigInfoService wechatConfigInfoService;

    @Override
    public List<WechatTemplateMsg> findByIds(List<String> ids) {
        Query query = new Query().addCriteria(Criteria.where("id").in(ids));
        return mongoTemplate.find(query, WechatTemplateMsg.class);
    }

    @Override
    public List<WechatTemplateMsg> find(String platform, String appId) {
        Query query = new Query().addCriteria(Criteria.where("appId").is(appId).and("platform").is(platform));
        return mongoTemplate.find(query, WechatTemplateMsg.class);
    }

    @Override
    public Page<WechatTemplateMsg> list(WechatTemplateMsgQueryVO req) {
        Query query = new Query();
        if (StringUtils.isNotBlank(req.getAppId())) {
            query.addCriteria(Criteria.where("appId").is(req.getAppId()));
        }
        if (StringUtils.isNotBlank(req.getPlatform())) {
            query.addCriteria(Criteria.where("platform").is(req.getPlatform()));
        }
        if (StringUtils.isNotBlank(req.getName())) {
            Pattern pattern = Pattern.compile("^.*" + req.getName() + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("name").regex(pattern));
        }
        long count = this.mongoTemplate.count(query, WechatTemplateMsg.class);
        PageRequest pageRequest = PageRequest.of(req.getPage() - 1, req.getPageSize());
        if (count == 0) {
            return PageableExecutionUtils.getPage(new ArrayList<>(), pageRequest, () -> count);
        }
//        query.with(new Sort(Sort.Direction.DESC, "createdTime"));
        Sort sort=Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        query.with(pageRequest);
        List<WechatTemplateMsg> list = this.mongoTemplate.find(query, WechatTemplateMsg.class);
        return PageableExecutionUtils.getPage(list, pageRequest, () -> count);
    }

    @Override
    public boolean create(WechatTemplateMsg req) {
        req.setId(null);
        req.setCreatedTime(new Date());
        if (StringUtils.isNotBlank(req.getAppId())) {
            WechatConfigInfo configInfo = wechatConfigInfoService.find(req.getAppId());
            if (Objects.nonNull(configInfo)) {
                req.setAppName(configInfo.getName());
            }
        }
        req = mongoTemplate.insert(req);
        if (StringUtils.isNotBlank(req.getId())) {
            return true;
        }
        return false;
    }

    @Override
    public boolean update(@NotNull WechatTemplateMsg req) {
        if (StringUtils.isBlank(req.getId())) {
            log.error(":>>> 修改微信模版消息参数错误");
            return false;
        }
        WechatTemplateMsg exist = this.findOne(req.getId());
        if (Objects.isNull(exist)) {
            log.error(":>>> 修改微信模版消息数据不存在:{}", req.getId());
            return false;
        }
        Query query = new Query().addCriteria(Criteria.where("id").is(req.getId()));
        Update update = new Update();
        boolean toUpdate = false;
        if (StringUtils.isNotBlank(req.getName())) {
            update.set("name", req.getName());
            toUpdate = true;
        }
        if (StringUtils.isNotBlank(req.getPlatform())) {
            update.set("platform", req.getPlatform());
            toUpdate = true;
        }
        if (StringUtils.isNotBlank(req.getTemplateId())) {
            update.set("templateId", req.getTemplateId());
            toUpdate = true;
        }
        if (StringUtils.isNotBlank(req.getAppId())) {
            update.set("appId", req.getAppId());
            toUpdate = true;
            if (!req.getAppId().equals(exist.getAppId())) {
                WechatConfigInfo configInfo = wechatConfigInfoService.find(req.getAppId());
                if (Objects.nonNull(configInfo)) {
                    update.set("appName", configInfo.getName());
                }
            }
        }
        if (Objects.nonNull(req.getStatus())) {
            update.set("status", req.getStatus());
            toUpdate = true;
        }
        if (toUpdate) {
            update.set("updatedTime", new Date());
            UpdateResult updateResult = mongoTemplate.updateFirst(query, update, WechatTemplateMsg.class);
            return updateResult.getModifiedCount() > 0 ? true : false;
        }
        return false;
    }

    @Override
    public boolean delete(String id) {
        Query query = new Query().addCriteria(Criteria.where("id").is(id));
        Update update = new Update();
        update.set("deleted", true);
        update.set("updatedTime", new Date());
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, WechatTemplateMsg.class);
        return updateResult.getModifiedCount() > 0 ? true : false;
    }

    @Override
    public WechatTemplateMsg findOne(String id) {
        Query query = new Query().addCriteria(Criteria.where("id").is(id));
        return mongoTemplate.findOne(query, WechatTemplateMsg.class);
    }
}
